from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from fastapi.security import OAuth2PasswordRequestForm
from pydantic import BaseModel
from datetime import timedelta
from app.core.database import get_db
from app.core import security
from app import models

router = APIRouter()

class LoginRequest(BaseModel):
    username: str
    password: str

class LoginResponse(BaseModel):
    access_token: str
    token_type: str = "bearer"
    user: dict

@router.post("/login", response_model=LoginResponse)
def login(data: LoginRequest, db: Session = Depends(get_db)):
    user = db.query(models.User).filter(models.User.username == data.username).first()
    if not user or not security.verify_password(data.password, user.hashed_password):
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=30)
    token = security.create_access_token(subject=str(user.id), expires_delta=access_token_expires)
    return LoginResponse(access_token=token, user={
        "id": user.id,
        "username": user.username,
        "email": user.email,
        "full_name": user.full_name,
        "role": user.role.value if hasattr(user.role, 'value') else user.role,
        "grade": user.grade,
        "created_at": user.created_at.isoformat() if getattr(user, 'created_at', None) else None,
        "updated_at": user.updated_at.isoformat() if getattr(user, 'updated_at', None) else None,
    })

@router.get("/me")
def me(db: Session = Depends(get_db)):
    # 简化: 演示用途，直接返回第一个用户
    user = db.query(models.User).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return {
        "id": user.id,
        "username": user.username,
        "email": user.email,
        "full_name": user.full_name,
        "role": user.role.value if hasattr(user.role, 'value') else user.role,
        "grade": user.grade,
        "created_at": user.created_at.isoformat() if getattr(user, 'created_at', None) else None,
        "updated_at": user.updated_at.isoformat() if getattr(user, 'updated_at', None) else None,
    }
